'use strict';

define([
  'angular',
  'angularAMD',
  'angular-route',
  'angular-animate',
  'angular-cookies',
  'angular-touch',
  'ng-dialog',
  'modules-pc/route'
], function(ng, angularAMD) {

  var app = ng.module('BHZApp', ['ngRoute', 'ngAnimate', 'ngCookies', 'ngTouch', 'ngDialog', 'BHZRoute']);

  app.constant("BHZConfig", {
    MODULE_PATH: 'catalog/view/theme/bhz/pc/modules/'
  });

  app.config(function($provide, $httpProvider) {

    // Intercept http calls.
    $provide.factory('MyHttpInterceptor', function($q) {
      return {
        // On request success
        request: function(config) {
          // console.log(config); // Contains the data about the request before it is sent.

          // Return the config or wrap it in a promise if blank.
          return config || $q.when(config);
        },

        // On request failure
        requestError: function(rejection) {
          // console.log(rejection); // Contains the data about the error on the request.

          // Return the promise rejection.
          return $q.reject(rejection);
        },

        // On response success
        response: function(response) {
          // console.log(response); // Contains the data from the response.
          if (response.status === 401 || response.error && response.error.status === 401) {
            BHZ.MessageBox.show("正在跳转登录...");
            setTimeout(function() {
              window.location.hash = '#/login';
              // window.location.hash = '#/login?redirect_url=' + encodeURIComponent(window.location.href);
            }, 1000);
            return $q.reject(response);
          }

          //show the error message when like get simple data
          if (response.data.success == false || response.data.error) {
            var error_msg = typeof response.data.error == 'object' ? response.data.error.warning : response.data.error;
            BHZ.MessageDialog.show(error_msg, "知道了");
            return $q.reject(response);
          }
          // Return the response or promise.
          return response || $q.when(response);
        },

        // On response failture
        responseError: function(rejection) {
          // console.log(rejection); // Contains the data about the error.
          if (rejection.status === 401 || rejection.error && rejection.error.status === 401) {
            BHZ.MessageBox.show("正在跳转登陆...");
            setTimeout(function() {
              window.location.hash = '#/login';
              // window.location.hash = '#/login?redirect_url=' + encodeURIComponent(window.location.href);
            }, 1000);
            //window.location.href = window.M_SERVER + '/login?redirect_url=' + encodeURIComponent(window.location.href);
          }
          // Return the promise rejection.
          return $q.reject(rejection);
        }
      };
    });

    // Add the interceptor to the $httpProvider.
    $httpProvider.interceptors.push('MyHttpInterceptor');

  });

  app.run(
    ['$rootScope', '$location', '$cookieStore', '$http', '$window',
      function($rootScope, $location, $cookieStore, $http, $window) {

        $rootScope.baseURI = document.baseURI;
        $rootScope.isWeixin = window.isWeixin;
        $rootScope.bhz_user = $cookieStore.get('bhz_user'); 
        
        $rootScope.$on("$routeChangeSuccess", function(event, current, previous) {
          if (current) {
            //set page title
            $rootScope.page_title = current.title || '百货栈';
            $rootScope.withHeader = current.withHeader;
            $rootScope.withFooter = current.withFooter;
            $rootScope.withTopHeader = current.withTopHeader;
            $rootScope.withSearch = current.withSearch;
            $rootScope.withCart = current.withCart;
            $rootScope.redHeader = current.redHeader;
            $rootScope.isLoginOrRegister = current.isLoginOrRegister;
            $rootScope.withSubtitleLogo = current.withSubtitleLogo;
          }
          var url = $location.url();
          initCartData();
          if(url.indexOf("home") != -1){
              if($("#TopBanner").length>0){
                $("#TopBanner").show();
              } 
          }else{
            if($("#TopBanner").length>0){
                $("#TopBanner").hide();
              } 
          }
        });

        $rootScope.jump = function(path,withoutParams, newPage){
          if(newPage){
            var absUrl = $location.absUrl();
            absUrl = absUrl.split('#')[0];
            $window.open(absUrl+'#'+path, '_blank');
          }
          else{
            if(withoutParams){
              $location.url(path);
            }else{
              $location.path(path);
            }
          }
          
        };
        
        

        $rootScope.logout = function(){
          $http.post('index.php?route=rest/logout/logout')
          .then(function(result){
            if(result.data.success){
              BHZ.MessageBox.show("退出成功");
              $cookieStore.remove('bhz_user');
              $location.path('/home');
              $window.location.reload();
            }
          })
        }

        $rootScope.gotoProduct = function(productId){
          $location.path('/product/'+productId);
        }

        function initCartData() {
          if($rootScope.bhz_user && $rootScope.bhz_user.need_review == 0){
            $http.get('index.php?route=rest/cart/cart').then(function(result) {
              if (result.data && result.data.success) {
                if(result.data.data.products){
                  $rootScope.cartCnt = result.data.data.products.length;
                }
              }
            })
          }else{
            $rootScope.cartCnt = false;
          }
        }
        //Liqn 暂时性comment out以防error alert影响体验
        initCartData();




        var is_backTop_show = false;
        //when page scrolling down, show the back top button
        $(window).scroll(function() {
          if ($(this).scrollTop() > 500) {
            if(is_backTop_show == false){
              $('#back-top').fadeIn('fast');
              is_backTop_show = true;
            }
          } else {
            if(is_backTop_show == true){
              $('#back-top').fadeOut('fast');
              is_backTop_show = false;
            }
          }
        });

        $rootScope.backTop = function(){
          $('body,html').animate({
            scrollTop: 0
          }, 'fast');
        }

      }
    ]);

  return app;

});
